package cn.com.coding.framework.security;

import cn.com.coding.common.utils.JwtUtil;
import cn.com.coding.system.domin.SysUserEntity;
import cn.com.coding.system.domin.UserInfoEntity;
import cn.com.coding.system.service.SysUserService;
import cn.com.coding.system.service.UserInfoService;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT 过滤器
 * 只有登陆后方可进行操作
 *
 * @author mxz
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserInfoService userInfoService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String jwt = request.getHeader(jwtUtil.getHeader());
        if (StrUtil.isBlankOrUndefined(jwt)) {
            // 直接往后面去走
            chain.doFilter(request, response);
            return;
        }

        // 解析jwt
        Claims claim = jwtUtil.getClaimByToken(jwt);
        if (claim == null) {
            throw new JwtException("token 异常");
        }
        // 判断token是否过期
        if (jwtUtil.isTokenExpired(claim)) {
            throw new JwtException("token已过期");
        }


        String username = claim.getSubject();
        // 获取用户的权限等信息

        SysUserEntity sysUserEntity = sysUserService.getByUserName(username);
        UserInfoEntity userInfoEntity = userInfoService.getByUserName(username);
        UsernamePasswordAuthenticationToken token = null;
        if (sysUserEntity == null) {
            token = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(userInfoEntity.getPid()));
        } else {
            token = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(sysUserEntity.getPid()));
        }


        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);
    }
}
